package com.lrl.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
public class DruidConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    //后台监控
    @Bean
    public ServletRegistrationBean StatViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean =
                new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        //后台需要有人登录
        HashMap<String, String> initParameters = new HashMap<>();

        //登录的loginUserName，loginPassword写死的
        initParameters.put("loginUserName", "admin");
        initParameters.put("loginPassword", "123456");

        //允许谁访问
        //initParams.put("allow","");//默认就是允许所有访问
        initParameters.put("allow", "localhost");//表示只有本机可以访问


        //禁止谁访问
//        initParameters.put("deny","localhost");

        //禁用登录界面的reset按钮
        bean.addInitParameter("resetEnable", "false");

        bean.setInitParameters(initParameters);//初始化参数
        return bean;
    }

    @Bean
    public FilterRegistrationBean webStartFilter() {
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());

        //可以过滤的请求
        HashMap<String, String> initParameters = new HashMap<>();

        //过滤所有请求
        bean.addUrlPatterns("/*");
        //过滤排除，详情进源码WebStatFilter类中
        initParameters.put("exclusions", "*.js,*.css,*.ico,/druid/*");

        bean.setInitParameters(initParameters);
        return bean;
    }
}
